<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Facades\Services\CommodityService;
use ValiDate;
use Illuminate\Validation\Rule;

class CommodityController extends Controller
{	

	public function getTypes(){
		return formatJsonResponse(CommodityService::getTypes());
	}

	public function addType(Request $request){
		$rules = [
			'ct_name' => 'required|unique:commodity_types'
		];

		ValiDate::valiDate($request,$rules);

		$data = $request->all();

		CommodityService::addType($data);

		return formatJsonResponse();
	}

	public function updateType(Request $request){
		$rules = [
			'id' => 'required|exists:commodity_types,id',
			'ct_name' => ['required',Rule::unique('commodity_types')->ignore($request->ct_name,'ct_name')]
		];

		ValiDate::valiDate($request,$rules);

		CommodityService::updateType($request->id,$request->only(['ct_name']));

		return formatJsonResponse();
	}

	public function deleteType(Request $request){
		$rules = [
			'id' => 'required|exists:commodity_types,id'
		];

		ValiDate::valiDate($request,$rules);

		CommodityService::deleteType($request->id);

		return formatJsonResponse();
	}

    public function addCommodity(Request $request){

    	$rules = [
    		'c_name' => 'required',
    		'c_number' => 'required',
    		'c_integration' => 'required',
    		'c_picture' => 'required|array',
    		'ct_type_id' => 'required|exists:commodity_types,id'
    	];

    	ValiDate::valiDate($request,$rules);

		$data = $request->all();

    	CommodityService::addCommodity($data);

    	return formatJsonResponse();
    }

    public function getCommodities(){

    	return formatJsonResponse(CommodityService::getCommodities(null));
    }

    public function getCommodity(Request $request){

    	$rules = [
    		'id' => 'required|exists:commodities,id',
    	];

    	ValiDate::valiDate($request,$rules);

    	return formatJsonResponse(CommodityService::getCommodity($request->id));
    }

    public function updateCommodity(Request $request){
    	$rules = [
    		'id' => 'required|exists:commodities,id',
    		'c_name' => 'required',
    		'c_number' => 'required',
    		'c_integration' => 'required',
    		'c_picture' => 'required|array',
    		'ct_type_id' => 'required|exists:commodity_types,id'
    	];

    	ValiDate::valiDate($request,$rules);

    	$data = $request->all();

    	CommodityService::updateCommodity($data);

    	return formatJsonResponse();
    }

    public function deleteCommodity(Request $request){
    	$rules = [
    		'id' => 'required|exists:commodities,id'
    	];

    	ValiDate::valiDate($request,$rules);

    	CommodityService::deleteCommodity($request->id);

    	return formatJsonResponse();
    }
}
